﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SurfaceAd.Common;
using SurfaceAd.Entities;
using Windows.Networking.Connectivity;

/**
 * 创建时间：2014/9/23 14:27:21
 * 作者：yong.blackcore
 * Email：itblackhole@outlook.com
 * QQ：50404503
 */
namespace SurfaceAd.Assistant
{
    internal static class NetworkHelper
    {
        public static NetworkInfo NetInfo { get; private set; }

        /// <summary>
        /// 网络是否可用
        /// </summary>
        /// <returns></returns>
        internal static bool IsConnectedToInternet()
        {
            bool isConnected = false;

            var cp = NetworkInformation.GetInternetConnectionProfile();
            if (cp != null)
            {
                NetworkConnectivityLevel cl = cp.GetNetworkConnectivityLevel();
                isConnected = (cl == NetworkConnectivityLevel.InternetAccess);
            }

            return isConnected;
        }

        /// <summary>
        /// 获取网络连接信息
        /// </summary>
        internal static NetworkInfo GetDeviceNetworkInfo()
        {
            NetworkInfo info = new NetworkInfo()
            {
                IsConnectedToInternet = false,
                NetcardId = string.Empty,
                NetInboundMaxBitsPerSecond = 0,
                NetOutboundMaxBitsPerSecond = 0,
                NetAdapterType = new NetAdapterInterfaceType() { Id = Convert.ToInt32(DeviceNetworkType.None), Name = DeviceNetworkType.None.ToString() }
            };
            try
            {
                // 获取当前用于 Internet 连接的 ConnectionProfile 对象
                var connectionProfile = NetworkInformation.GetInternetConnectionProfile();
                if (connectionProfile == null)
                {
                    NetInfo = info;
                    return info;
                }
                // 此连接的网络连接级别（Windows.Networking.Connectivity.NetworkConnectivityLevel 枚举）
                //     None - 无连接
                //     LocalAccess - 仅允许访问本地网络
                //     ConstrainedInternetAccess - 受限的 internet 访问
                //     InternetAccess - 本地和 internet 访问                
                var networkConnectLevel = connectionProfile.GetNetworkConnectivityLevel();
                //
                info.IsConnectedToInternet = (networkConnectLevel == NetworkConnectivityLevel.InternetAccess);
                var networkAdapter = connectionProfile.NetworkAdapter;
                if (networkAdapter != null)
                {
                    info.NetcardId = networkAdapter.NetworkAdapterId.ToString(); // 当前网络适配器 的ID，有多网卡时连接不一样ID也不一样
                    info.NetInboundMaxBitsPerSecond = networkAdapter.InboundMaxBitsPerSecond / 8 / 1024; // 最大入站数据传输速率（单位：bit/s）
                    info.NetOutboundMaxBitsPerSecond = networkAdapter.OutboundMaxBitsPerSecond / 8 / 1024; // 最大出站数据传输速率（单位：bit/s）
                    var networkType = networkAdapter.NetworkItem.GetNetworkTypes(); // 网络类型
                }
                //
                info.NetAdapterType = GetNetworkAdapterInterfaceType(connectionProfile);
            }
            catch (Exception err)
            {
                LogHelper.LogError(err.ToString(), typeof(NetworkHelper), "GetDeviceNetworkInfo");
            }
            NetInfo = info;
            return info;
        }

        private static NetAdapterInterfaceType GetNetworkAdapterInterfaceType(ConnectionProfile connectionProfile)
        {
            NetAdapterInterfaceType result = new NetAdapterInterfaceType()
            {
                Id = Convert.ToInt32(DeviceNetworkType.None),
                Name = DeviceNetworkType.None.ToString()
            };
            if (connectionProfile == null)
            {
                return result;
            }
            try
            {   
                //http://msdn.microsoft.com/en-us/library/windows/apps/windows.networking.connectivity.networkadapter.ianainterfacetype.aspx
                var interfaceType = connectionProfile.NetworkAdapter.IanaInterfaceType;

                if (interfaceType == 71)//wifi
                {
                    result.Id = Convert.ToInt32(DeviceNetworkType.Wifi);
                    result.Name = DeviceNetworkType.Wifi.ToString();
                }
                else if (interfaceType == 6)//ethernet
                {
                    result.Id = Convert.ToInt32(DeviceNetworkType.HasLineInternal);
                    result.Name = DeviceNetworkType.HasLineInternal.ToString();
                }
                else
                {
                    result.Id = Convert.ToInt32(interfaceType);
                    result.Name = interfaceType.ToString();
                }
            }
            catch (Exception err)
            {
                LogHelper.LogError(err.ToString(), typeof(NetworkHelper), "GetNetworkAdapterInterfaceType");
            }
            return result;
        }

        /// <summary>
        /// 获得网络类型
        /// </summary>
        /// <returns></returns>
        internal static NetAdapterInterfaceType GetNetworkAdapterInterfaceType()
        {
            //if (NetworkInformation.GetInternetConnectionProfile() != null)
            //{
            //    return "wi-fi";
            //}
            //return "no-netwrok";
            //http://msdn.microsoft.com/en-us/library/windows/apps/windows.networking.connectivity.networkadapter.ianainterfacetype.aspx
            var profile = NetworkInformation.GetInternetConnectionProfile();
            return GetNetworkAdapterInterfaceType(profile);
        }

    }
}
